package com.example.designpattern.strategy;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 策略模式测试类
 *
 * @author long
 * @date 2024/11/12 13:28
 */
@Service
public class TestStrategySimpleService implements InitializingBean {

    @Autowired
    private List<IStudyService> studyServiceList;

    private Map<StudyLanguageEnum,IStudyService> studyServiceMap;

    @Override
    public void afterPropertiesSet() throws Exception {
        if(CollectionUtils.isEmpty(studyServiceList)){
            this.studyServiceMap = new HashMap<>();
            return;
        }

        this.studyServiceMap = studyServiceList.stream().collect(Collectors.toMap(IStudyService::studyLanguage,Function.identity(),(x,y)->x));
    }

    /**
     * 处理请求
     * @param studyType
     */
    public void handleRequest(String studyType){

        // 原始逻辑
        strategyModelSimple(studyType);

        // 策略模式逻辑
        strategyModelSimple2(studyType);
    }

    /**
     * 策略模式改造1
     * @param studyType
     */
    private void strategyModelSimple(String studyType){
        StudyLanguageEnum studyLanguageEnum = StudyLanguageEnum.of(studyType);
        studyServiceMap.get(studyLanguageEnum).doStudy(studyType);
    }

    /**
     * beanName -> service对象
     */
    @Autowired
    private Map<String,IStudyService> nameServiceMap;

    /**
     * 策略模式改造2
     * @param studyType
     */
    private void strategyModelSimple2(String studyType){
        StudyLanguageEnum studyLanguageEnum = StudyLanguageEnum.of(studyType);
        nameServiceMap.get(studyLanguageEnum.getBeanName()).doStudy(studyType);
    }


}
